import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { familyMemberApi } from "@/services/familyMemberService";
import type {
  FamilyMemberResponse,
  FamilyMemberCreate,
  FamilyMemberUpdate,
  FamilyMemberListParams,
} from "@/types/family";

export const useFamilyStore = defineStore("family", () => {
  // 状态
  const familyMembers = ref<FamilyMemberResponse[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);
  const currentMember = ref<FamilyMemberResponse | null>(null);

  // 计算属性
  const activeMembers = computed(() =>
    familyMembers.value.filter((member) => member.is_active),
  );

  const adminMembers = computed(() =>
    familyMembers.value.filter((member) => member.role === "admin"),
  );

  const memberCount = computed(() => familyMembers.value.length);
  const activeMemberCount = computed(() => activeMembers.value.length);

  // 获取家庭成员列表
  async function fetchFamilyMembers(params?: FamilyMemberListParams) {
    try {
      loading.value = true;
      error.value = null;
      familyMembers.value = await familyMemberApi.getFamilyMembers(params);
    } catch (err) {
      console.error("获取家庭成员列表失败:", err);
      error.value = "获取家庭成员列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 获取单个家庭成员
  async function fetchFamilyMember(memberId: number) {
    try {
      loading.value = true;
      error.value = null;
      const member = await familyMemberApi.getFamilyMember(memberId);
      currentMember.value = member;
      return member;
    } catch (err) {
      console.error("获取家庭成员详情失败:", err);
      error.value = "获取家庭成员详情失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 创建家庭成员
  async function createFamilyMember(memberData: FamilyMemberCreate) {
    try {
      loading.value = true;
      error.value = null;
      const newMember = await familyMemberApi.createFamilyMember(memberData);
      familyMembers.value.push(newMember);
      return newMember;
    } catch (err) {
      console.error("创建家庭成员失败:", err);
      error.value = "创建家庭成员失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 更新家庭成员
  async function updateFamilyMember(
    memberId: number,
    memberData: FamilyMemberUpdate,
  ) {
    try {
      loading.value = true;
      error.value = null;
      const updatedMember = await familyMemberApi.updateFamilyMember(
        memberId,
        memberData,
      );
      const index = familyMembers.value.findIndex((m) => m.id === memberId);
      if (index !== -1) {
        familyMembers.value[index] = updatedMember;
      }
      if (currentMember.value?.id === memberId) {
        currentMember.value = updatedMember;
      }
      return updatedMember;
    } catch (err) {
      console.error("更新家庭成员失败:", err);
      error.value = "更新家庭成员失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 删除家庭成员
  async function deleteFamilyMember(memberId: number) {
    try {
      loading.value = true;
      error.value = null;
      await familyMemberApi.deleteFamilyMember(memberId);
      familyMembers.value = familyMembers.value.filter(
        (m) => m.id !== memberId,
      );
      if (currentMember.value?.id === memberId) {
        currentMember.value = null;
      }
    } catch (err) {
      console.error("删除家庭成员失败:", err);
      error.value = "删除家庭成员失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 检查是否为管理员
  async function checkIsAdmin(memberId: number) {
    try {
      const result = await familyMemberApi.checkIsAdmin(memberId);
      return result.is_admin || false;
    } catch (err) {
      console.error("检查管理员权限失败:", err);
      return false;
    }
  }

  // 获取家庭管理员列表
  async function fetchFamilyAdmins() {
    try {
      loading.value = true;
      error.value = null;
      const admins = await familyMemberApi.getFamilyAdmins();
      return admins;
    } catch (err) {
      console.error("获取家庭管理员列表失败:", err);
      error.value = "获取家庭管理员列表失败";
      throw err;
    } finally {
      loading.value = false;
    }
  }

  // 清除错误
  function clearError() {
    error.value = null;
  }

  // 重置状态
  function reset() {
    familyMembers.value = [];
    currentMember.value = null;
    error.value = null;
    loading.value = false;
  }

  return {
    // 状态
    familyMembers,
    loading,
    error,
    currentMember,

    // 计算属性
    activeMembers,
    adminMembers,
    memberCount,
    activeMemberCount,

    // 方法
    fetchFamilyMembers,
    fetchFamilyMember,
    createFamilyMember,
    updateFamilyMember,
    deleteFamilyMember,
    checkIsAdmin,
    fetchFamilyAdmins,
    clearError,
    reset,
  };
});
